package net.courier.mq.provider.gearman;

import java.util.HashMap;
import java.util.Map;

import net.courier.mq.MessageHandler;
import net.courier.mq.Protocol;

import org.gearman.client.GearmanJobResult;
import org.gearman.client.GearmanJobResultImpl;
import org.gearman.worker.AbstractGearmanFunction;

public class FunctionHandler extends AbstractGearmanFunction {
	private final MessageHandler handler;
	private final String functionName;
	private final Protocol<?, byte[]> protocol;

	public FunctionHandler(MessageHandler handler, String functionName, Protocol<?, byte[]> protocol) {
		this.handler = handler;
		this.functionName = functionName;
		this.protocol = protocol;
	}

	@Override
	public GearmanJobResult executeFunction() {
		Map<String, Object> context = new HashMap<String, Object>(2, 1f);
		context.put("GearmanFunction", this);

		if (handler != null) {
			Object object = protocol.decode((byte[]) data);
			handler.handle(functionName, object, context);
		}
		return new GearmanJobResultImpl(jobHandle, true, null, null, null, 0, 0);

	}
}
